﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.UI.WebControls;
using DataAccessObject;
using ThangNM_LIB.DB;
using ThangNM_LIB.EO;
using ThangNM_LIB.FUNC;
using SharedLibraries;

namespace ThangNM.UserControl.Admin
{
    public partial class Account_NewUC : System.Web.UI.UserControl
    {
        #region "Properties & Event"
        public SortDirection directionState
        {
            get { return (ViewState["directionState"] == null ? SortDirection.Descending : (SortDirection)ViewState["directionState"]); }
            set { ViewState["directionState"] = value; }
        }

        public Int16 iFunctionType
        {
            get { return (Int16)ViewState["iFunctionType"]; }
            set { ViewState["iFunctionType"] = value; }
        }

        public AccountEO objTemp
        {
            get { return (AccountEO)ViewState["objTemp"]; }
            set { ViewState["objTemp"] = value; }
        }
        #endregion



        #region "Common"
        protected void Page_Load(object sender, EventArgs e)
        {
            MsgUC1.setClearMsg();
            if (!IsPostBack)
            {
                Title_FormUC1.setTitle(ConstEx.Table_Name_C.Account, ConstEx.funcButtonToolBar.LIST);
                ToolBarUC1.BindData_DropDownList(GetListConstants.Category_bStatus_GLC());
                LoadInterface(true, ConstEx.FunctionType.Default);
                BindData_DropDownList();
            }
        }

        public void LoadInterface(Boolean isList, Int16 iFunc)
        {
            if (isList)
            {
                SearchUI1.ResetFormSearch();
                mtvMain.SetActiveView(vList);
                ToolBarUC1.ViewGroupButtonByFunction(ConstEx.funcButtonToolBar.LIST);
                ToolBarUC1.SetDefaultValue(true);
                BindData_List(null, grvList);
            }
            else
            {
                mtvMain.SetActiveView(vDetail);
                BindData_Detail(objTemp, iFunc);
                ToolBarUC1.ViewGroupButtonByFunction(ConstEx.funcButtonToolBar.DETAIL);
            }
        }

        protected void EventButtonToolBar_Click(object sender, CustomerEventArgs e)
        {
            //if (e.iType != ConstEx.funcButtonToolBar.BACK_LIST && (new ShareDAO.UserDAO()).SelectBy_sPermission(Session["secret"], Convert.ToString(Request.Url.AbsolutePath), e.iType) == false)
            //{
            //    setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.DANGER, MessagesEx.Khong_Co_Quyen_Truy_Cap, null));
            //    Commons.setAccessDenied(Page, null);
            //    return;
            //}
            switch (e.iType)
            {
                case ConstEx.funcButtonToolBar.INSERT_ITEM:
                    InsertItem();
                    break;
                case ConstEx.funcButtonToolBar.UPDATE_ITEM:
                    UpdateItem();
                    break;
                case ConstEx.funcButtonToolBar.DELETE_ITEM:
                    DeleteItem();
                    break;
                case ConstEx.funcButtonToolBar.RESET_FORM:
                    ResetForm();
                    break;
                case ConstEx.funcButtonToolBar.BACK_LIST:
                    LoadInterface(true, ConstEx.FunctionType.Default);
                    break;
                case ConstEx.funcButtonToolBar.INSERT_LIST:
                    objTemp = new AccountEO();
                    LoadInterface(false, ConstEx.FunctionType.Insert);
                    break;
                case ConstEx.funcButtonToolBar.DELETE_LIST:
                    DeleteList();
                    break;
                case ConstEx.funcButtonToolBar.REFRESH_LIST:
                    SearchUI1.ResetFormSearch();
                    BindData_List(null, grvList);
                    break;
                case ConstEx.funcButtonToolBar.EXPORT_EXCEL:
                    if (grvList.PageCount > 0)
                    {
                        //GridView grvTemp = grvList;
                        BindData_List(null, grvList);
                        ExportEx.PDF_Export(grvList, "Account");
                    }
                    else
                        MsgUC1.setNotifications(ConstEx.FunctionSetMsg.WARNING, "Không thể xuất file vì không có bản ghi nào.");
                    break;
            }
        }
        #endregion




        #region "List"
        public void BindData_List(String sSortColumn, GridView _grvTemp)
        {
            try
            {
                List<Account_ZipEO> lst = new List<Account_ZipEO>();
                _grvTemp.Visible = false;
                string keysearch = StringEx.Trim(SearchUI1.txtTextSearch.Text).ToUpper();
                DataTable dt = (new ShareDAO.UserDAO()).SelectBy_bState(ToolBarUC1.ddlStatus.SelectedValue);
                DataView dv = dt.DefaultView;
                if (!String.IsNullOrEmpty(sSortColumn))
                    dv.Sort = sSortColumn;
                else
                    dv.Sort = "[PK_iAccountID] DESC";
                dt = dv.ToTable();
                var result = (List<Account_ZipEO>)ConvertEx.ConvertDataTableToListObject<Account_ZipEO>(dt, lst.GetType());
                if (result != null)
                {
                    if (SearchUI1.ddlTypeSearch.SelectedValue.Equals("0"))
                    {
                        if (!String.IsNullOrEmpty(keysearch))
                            result = result.FindAll(x => StringEx.CompareEx(x.PK_iAccountID.ToString(), keysearch));
                    }
                    else
                    {
                        if (!String.IsNullOrEmpty(keysearch))
                            result = result.FindAll(x => StringEx.CompareEx(x.sUsername, keysearch));
                    }
                    if (result.Count() > 0)
                    {
                        _grvTemp.Visible = true;
                        _grvTemp.DataSource = result.ToList();
                        _grvTemp.DataBind();
                        lblRowCount.Text = MessagesEx.Tong_So_Ban_Ghi + result.Count();
                        return;
                    }
                }
                _grvTemp.DataSource = null;
                _grvTemp.DataBind();
                lblRowCount.Text = MessagesEx.Khong_Thoa_Man_Dieu_Kien_Tim_Kiem;
            }
            catch (Exception ex)
            {
                MsgUC1.setNotifications(ConstEx.FunctionSetMsg.ERROR, ex.Message, ex.ToString());
            }
        }

        protected void SearchUI_Click(object sender, EventArgs e)
        {
            BindData_List(null, grvList);
        }

        protected void EventSelectChange_Click(object sender, CustomerEventArgs e)
        {
            BindData_List(null, grvList);
        }

        protected void grvList_RowCommand(object source, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "cmdView")
            {
                int rowIndex = Convert.ToInt32(e.CommandArgument) % grvList.PageSize;
                int PK_iAccountID = Convert.ToInt32(grvList.DataKeys[rowIndex].Values[0]);
                AccountEO _AccountEO = new AccountEO();
                _AccountEO = (new ShareDAO.UserDAO()).SelectItem(PK_iAccountID, null);
                if (_AccountEO != null)
                {
                    objTemp = _AccountEO;
                    LoadInterface(false, ConstEx.FunctionType.View);
                }
                else
                    MsgUC1.setNotifications(ConstEx.FunctionSetMsg.WARNING, "Tài khoản vừa chọn không tồn tại");
            }
        }

        protected void grvList_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grvList.PageIndex = e.NewPageIndex;
            BindData_List(null, grvList);
        }

        protected void grvList_Sorting(object sender, GridViewSortEventArgs e)
        {
            if (directionState == SortDirection.Ascending)
            {
                directionState = SortDirection.Descending;
                BindData_List("[" + e.SortExpression + "]" + " DESC", grvList);
            }
            else
            {
                directionState = SortDirection.Ascending;
                BindData_List("[" + e.SortExpression + "]" + " ASC", grvList);
            }
        }

        protected void DeleteList()
        {
            try
            {
                //string strID = "";
                //string strUsername = "";
                //foreach (GridViewRow row in grvList.Rows)
                //{
                //    CheckBox chk = (CheckBox)row.FindControl("chkItem");
                //    if (chk != null && chk.Checked)
                //    {
                //        strID += "," + grvList.DataKeys[row.RowIndex].Values["PK_iAccountID"];
                //        strUsername += "," + System.Configuration.ConfigurationManager.AppSettings["HOMEPAGE"] + FileNameByFunction.Tac_Gia_ + RewriteUrl.ConvertToUnSign(Convert.ToString(grvList.DataKeys[row.RowIndex].Values["sUsername"]));
                //    }
                //}
                //if (String.IsNullOrEmpty(strID))
                //{
                //    MsgUC1.setNotifications(ConstEx.FunctionSetMsg.WARNING, String.Format(MessagesEx.CHUA_CHON_DONG_NAO_DE_XOA, ConstEx.Table_Name_C.Account));
                //    return;
                //}


                //if (ShareDAO.UserDAO.Delete(strID.Substring(1), strUsername.Substring(1)))
                //{
                //    BindData_List(null);
                //        setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.SUCCESS, String.Format(MessagesEx.Xoa_Thanh_Cong_Ma, ConstEx.Table_Name_C.Account, strID.Substring(1)), null));
                //}
                //else
                //{
                //    setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.WARNING, String.Format(MessagesEx.Xoa_That_Bai_Ma, ConstEx.Table_Name_C.Account, strID.Substring(1)), null));
                //}
            }
            catch (Exception ex)
            {
                MsgUC1.setNotifications(ConstEx.FunctionSetMsg.ERROR, ex.Message, ex.ToString());
            }
        }
        #endregion




        #region "Detail"
        public void BindData_Detail(AccountEO objInput, Int16 iFuncType)
        {
            objTemp = objInput;
            BindData_DropDownList();
            txtsUsername.Text = Convert.ToString(objInput.sUsername);
            txtsPassword.Text = Convert.ToString(objInput.sPassword);
            txtsEmail.Text = Convert.ToString(objInput.sEmail);
            txtsFullName.Text = Convert.ToString(objInput.sFullName);
            txtsAddress.Text = Convert.ToString(objInput.sAddress);
            WebEx.setText_InputDateTime(txttDateOfBirth, objInput.tDateOfBirth, false);
            txtsPhoneNumber.Text = Convert.ToString(objInput.sPhoneNumber);
            WebEx.setSelect_DropDownList(ddliPermission, Convert.ToString(objInput.iPermission));
            txtsLinkAvatar.Text = Convert.ToString(objInput.sLinkAvatar);
            txtiLike.Text = Convert.ToString(objInput.iLike);
            chkbStatus.Checked = objInput.bStatus;
            WebEx.setText_InputDateTime(txttDateTimeCreate, objInput.tDateTimeCreate);
            WebEx.setText_InputDateTime(txttDateTimeModify, objInput.tDateTimeModify);
            iFunctionType = iFuncType;
            ViewByFunction(iFunctionType);
        }

        protected void BindData_DropDownList()
        {
            ddliPermission.DataSource = GetListConstants.Account_iPermission_GLC();
            ddliPermission.DataTextField = "Value";
            ddliPermission.DataValueField = "Key";
            ddliPermission.DataBind();
        }

        protected bool CheckInput()
        {
            string strNull = "";
            if (string.IsNullOrEmpty(txtsUsername.Text) == true)
            {
                strNull += ", " + lblsUsername.Text;
                txtsUsername.Focus();
            }
            if (string.IsNullOrEmpty(txtsPassword.Text) == true)
            {
                strNull += ", " + lblsPassword.Text;
                txtsPassword.Focus();
            }
            if (string.IsNullOrEmpty(txtsPasswordNew.Text) == true)
            {
                strNull += ", " + lblsPasswordNew.Text;
                txtsPasswordNew.Focus();
            }
            if (string.IsNullOrEmpty(txtsEmail.Text) == true)
            {
                strNull += ", " + lblsEmail.Text;
                txtsEmail.Focus();
            }
            if (string.IsNullOrEmpty(txtsFullName.Text) == true)
            {
                strNull += ", " + lblsFullName.Text;
                txtsFullName.Focus();
            }
            if (string.IsNullOrEmpty(txtsAddress.Text) == true)
            {
                strNull += ", " + lblsAddress.Text;
                txtsAddress.Focus();
            }
            if (string.IsNullOrEmpty(txttDateOfBirth.Text) == true)
            {
                strNull += ", " + lbltDateOfBirth.Text;
                txttDateOfBirth.Focus();
            }

            if (String.IsNullOrEmpty(strNull))
            {
                if (StringEx.Equals(Security.EnCrypt(txtsPasswordOld.Text, Security.MD5_Encrypt(objTemp.sUsername)), StringEx.Trim(objTemp.sPassword)) == false && (iFunctionType == ConstEx.FunctionType.View || iFunctionType == ConstEx.FunctionType.Update))
                {
                    MsgUC1.setNotifications(ConstEx.FunctionSetMsg.WARNING, MessagesEx.Mat_Khau_Cu_Khong_Trung_Khop);
                    txtsPasswordOld.Focus();
                    return false;
                }

                if (StringEx.Equals(txtsPassword.Text, txtsPasswordNew.Text) == false)
                {
                    MsgUC1.setNotifications(ConstEx.FunctionSetMsg.WARNING, MessagesEx.Mat_Khau_Nhap_Lai_Khong_Trung_Khop);
                    txtsPassword.Focus();
                    return false;
                }
                return true;
            }
            else
            {
                MsgUC1.setNotifications(ConstEx.FunctionSetMsg.WARNING, MessagesEx.CAC_TRUONG_BAT_BUOC_PHAI_NHAP + strNull.Substring(2).Replace(":", ""));
                return false;
            }
        }

        protected void GetObject(ref AccountEO _AccountEO)
        {
            try
            {
                _AccountEO.PK_iTable = ConstEx.TableID_C.Account;
                _AccountEO.PK_iSEO = objTemp.PK_iSEO;
                _AccountEO.sUsername = Convert.ToString(txtsUsername.Text);
                _AccountEO.sPassword = Security.EnCrypt(Convert.ToString(txtsPassword.Text), Security.MD5_Encrypt(_AccountEO.sUsername));
                _AccountEO.sEmail = Convert.ToString(txtsEmail.Text);
                _AccountEO.sFullName = Convert.ToString(txtsFullName.Text);
                _AccountEO.iPermission = Convert.ToInt16(ddliPermission.SelectedValue);
                //_AccountEO.sPermission = GetTextConstants.Account_iPermission_Default_GTC(_AccountEO.iPermission);
                _AccountEO.bStatus = chkbStatus.Checked;
                _AccountEO.iStatus = ConvertEx.Convert_bStatus_iStatus(_AccountEO.bStatus);
                _AccountEO.sAddress = Convert.ToString(txtsAddress.Text);
                _AccountEO.tDateOfBirth = Convert.ToDateTime(txttDateOfBirth.Text);
                _AccountEO.sPhoneNumber = Convert.ToString(txtsPhoneNumber.Text);
                _AccountEO.FK_sAccount = _AccountEO.sUsername;
                _AccountEO.FK_sCategory = "";
                _AccountEO.sTitle = _AccountEO.sUsername;
                _AccountEO.sLinkImage = OtherEx.getUrlStandard(txtsLinkAvatar.Text);
                _AccountEO.sKeyword = _AccountEO.sUsername + "," + _AccountEO.sFullName;
                _AccountEO.sDescription = _AccountEO.sUsername + "," + _AccountEO.sFullName + "," + _AccountEO.sAddress;
                _AccountEO.sUrlRewrite = Commons.get_sUrlRewrite_sUrlShort(_AccountEO.PK_iTable, true, null, _AccountEO.sUsername);
                _AccountEO.sUrlShort = Commons.get_sUrlRewrite_sUrlShort(_AccountEO.PK_iTable, false, null, _AccountEO.sUsername);
                _AccountEO.iChangefreq = Convert.ToInt16(4);
                _AccountEO.iRobots = Convert.ToInt16(0);
                _AccountEO.fPriority = Convert.ToDouble(0.3);
                _AccountEO.bStatus = chkbStatus.Checked;
                _AccountEO.iStatus = ConvertEx.Convert_bStatus_iStatus(_AccountEO.bStatus);
            }
            catch (Exception ex)
            {
                _AccountEO = null;
                MsgUC1.setNotifications(ConstEx.FunctionSetMsg.ERROR, ex.Message, ex.ToString());
            }
        }

        protected void setEnableAllInput()
        {
            txtsUsername.Enabled = false;
            divPasswordOld.Visible = false;
            txtsPasswordOld.Enabled = false;
            txtsPassword.Enabled = false;
            txtsPasswordNew.Enabled = false;
            txtsEmail.Enabled = false;
            txtsFullName.Enabled = false;
            txtsAddress.Enabled = false;
            txttDateOfBirth.Enabled = false;
            txtsPhoneNumber.Enabled = false;
            //ddliPermission.Enabled = false;
            txtsLinkAvatar.Enabled = false;
            txtiLike.Enabled = false;
            chkbStatus.Enabled = false;
            txttDateTimeCreate.Enabled = false;
            txttDateTimeModify.Enabled = false;
        }

        protected void ViewByFunction(Int16 iFuncType)
        {
            setEnableAllInput();
            switch (iFuncType)
            {
                case ConstEx.FunctionType.Insert:
                    txtsUsername.Enabled = true;
                    divPasswordOld.Visible = false;
                    txtsPasswordOld.Enabled = true;
                    txtsPassword.Enabled = true;
                    txtsPasswordNew.Enabled = true;
                    txtsEmail.Enabled = true;
                    txtsFullName.Enabled = true;
                    txtsAddress.Enabled = true;
                    txttDateOfBirth.Enabled = true;
                    txtsPhoneNumber.Enabled = true;
                    //ddliPermission.Enabled = true;
                    txtsLinkAvatar.Enabled = true;
                    chkbStatus.Enabled = true;
                    ToolBarUC1.ViewButtonByFunction(iFunctionType);
                    break;
                case ConstEx.FunctionType.Update:
                    divPasswordOld.Visible = true;
                    txtsPasswordOld.Enabled = true;
                    txtsPassword.Enabled = true;
                    txtsPasswordNew.Enabled = true;
                    txtsFullName.Enabled = true;
                    txtsAddress.Enabled = true;
                    txttDateOfBirth.Enabled = true;
                    txtsPhoneNumber.Enabled = true;
                    txtsLinkAvatar.Enabled = true;
                    ToolBarUC1.ViewButtonByFunction(iFunctionType);
                    break;
                case ConstEx.FunctionType.Delete: break;
                case ConstEx.FunctionType.View:
                    divPasswordOld.Visible = true;
                    txtsPasswordOld.Enabled = true;
                    txtsPassword.Enabled = true;
                    txtsPasswordNew.Enabled = true;
                    txtsFullName.Enabled = true;
                    txtsAddress.Enabled = true;
                    txttDateOfBirth.Enabled = true;
                    txtsPhoneNumber.Enabled = true;
                    txtsLinkAvatar.Enabled = true;
                    chkbStatus.Enabled = true;
                    ToolBarUC1.ViewButtonByFunction(iFunctionType);
                    break;
            }
        }

        protected void InsertItem()
        {
            try
            {
                if (CheckInput() == true)
                {
                    AccountEO _AccountEO = new AccountEO();
                    GetObject(ref _AccountEO);
                    if (_AccountEO == null)
                        return;
                    if ((new ShareDAO.UserDAO()).Insert_Update_Delete(_AccountEO, 1))
                        MsgUC1.setNotifications(ConstEx.FunctionSetMsg.SUCCESS, String.Format(MessagesEx.Them_Thanh_Cong_Ma_Ten, ConstEx.Table_Name_C.Account, _AccountEO.PK_iSEO, _AccountEO.sTitle));
                    else
                        MsgUC1.setNotifications(ConstEx.FunctionSetMsg.WARNING, String.Format(MessagesEx.Them_That_Bai_Ma_Ten, ConstEx.Table_Name_C.Account, _AccountEO.PK_iSEO, _AccountEO.sTitle));
                }
            }
            catch (Exception ex)
            {
                MsgUC1.setNotifications(ConstEx.FunctionSetMsg.ERROR, ex.Message, ex.ToString());
            }
        }

        protected void UpdateItem()
        {
            try
            {
                if (CheckInput() == true)
                {
                    AccountEO _AccountEO = new AccountEO();
                    GetObject(ref _AccountEO);
                    if (_AccountEO == null)
                        return;
                    if ((new ShareDAO.UserDAO()).Insert_Update_Delete(_AccountEO, 2))
                        MsgUC1.setNotifications(ConstEx.FunctionSetMsg.SUCCESS, String.Format(MessagesEx.Sua_Thanh_Cong_Ma_Ten, ConstEx.Table_Name_C.Account, _AccountEO.PK_iSEO, _AccountEO.sTitle));
                    else
                        MsgUC1.setNotifications(ConstEx.FunctionSetMsg.WARNING, String.Format(MessagesEx.Sua_That_Bai_Ma_Ten, ConstEx.Table_Name_C.Account, _AccountEO.PK_iSEO, _AccountEO.sTitle));
                }
            }
            catch (Exception ex)
            {
                MsgUC1.setNotifications(ConstEx.FunctionSetMsg.ERROR, ex.Message, ex.ToString());
            }
        }

        protected void DeleteItem()
        {
            try
            {
                AccountEO _AccountEO = new AccountEO();
                GetObject(ref _AccountEO);
                if (_AccountEO == null)
                    return;
                DataTable dt = (new TopicDAO()).SelectBy_FK_iAccountID(_AccountEO.PK_iAccountID);
                string lstID = "";
                if (DataTableEx.DataTable_OK(dt))
                {
                    foreach (DataRow item in dt.Rows)
                    {
                        lstID = lstID + "," + item["PK_iTopicID"];
                    }
                    MsgUC1.setNotifications(ConstEx.FunctionSetMsg.WARNING, String.Format(MessagesEx.Khong_Duoc_Xoa, ConstEx.Table_Name_C.Account, lstID.Substring(1), ConstEx.Table_Name_C.Topic));
                }
                dt = (new MediaDAO()).SelectBy_FK_iAccountID(_AccountEO.PK_iAccountID);
                if (DataTableEx.DataTable_OK(dt))
                {
                    lstID = "";
                    foreach (DataRow item in dt.Rows)
                    {
                        lstID = lstID + "," + item["PK_iMediaID"];
                    }
                    MsgUC1.setNotifications(ConstEx.FunctionSetMsg.WARNING, String.Format(MessagesEx.Khong_Duoc_Xoa, ConstEx.Table_Name_C.Account, lstID.Substring(1), ConstEx.Table_Name_C.Media));
                }
                if (!String.IsNullOrEmpty(lstID))
                    return;

                if ((new ShareDAO.UserDAO()).Insert_Update_Delete(_AccountEO, 3))
                    MsgUC1.setNotifications(ConstEx.FunctionSetMsg.SUCCESS, String.Format(MessagesEx.Xoa_Thanh_Cong_Ma_Ten, ConstEx.Table_Name_C.Account, _AccountEO.PK_iSEO, _AccountEO.sTitle));
                else
                    MsgUC1.setNotifications(ConstEx.FunctionSetMsg.WARNING, String.Format(MessagesEx.Xoa_That_Bai_Ma_Ten, ConstEx.Table_Name_C.Account, _AccountEO.PK_iSEO, _AccountEO.sTitle));
            }
            catch (Exception ex)
            {
                MsgUC1.setNotifications(ConstEx.FunctionSetMsg.ERROR, ex.Message, ex.ToString());
            }
        }

        protected void ResetForm()
        {
            BindData_Detail(new AccountEO(), iFunctionType);
        }
        #endregion
    }
}